package com.jeesite.modules.kj.api.controller.contribute;


import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.exception.RequireLoginException;
import com.jeesite.modules.common.interfaces.CurrentUser;
import com.jeesite.modules.common.interfaces.UserLoginToken;
import com.jeesite.modules.kj.api.vo.DataListPageVo;
import com.jeesite.modules.kj.api.wechatUtils.TokenUtils;
import com.jeesite.modules.kj.entity.*;
import com.jeesite.modules.kj.enums.IntegralEnum;
import com.jeesite.modules.kj.api.vo.request.ProjectListRequestVo;
import com.jeesite.modules.kj.api.vo.response.*;
import com.jeesite.modules.kj.api.vo.responseVo.ResponseBean;
import com.jeesite.modules.kj.exception.FreezMemberException;
import com.jeesite.modules.kj.exception.LowIntegralException;
import com.jeesite.modules.kj.service.KjContributeProjectService;
import com.jeesite.modules.kj.service.KjMemberIntegralHistoryService;
import com.jeesite.modules.kj.service.KjProjectTeamService;
import com.jeesite.modules.kj.service.KjTeamMemberService;
import com.jeesite.modules.kj.utils.IntegralUtil;
import com.jeesite.modules.kj.utils.KjMemberUtil;
import com.jeesite.modules.kj.utils.LikesUtil;
import com.jeesite.modules.kj.utils.TeamUtil;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.utils.DictUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * Author:hzy
 * Date:2021/07/04
 * Description:
 */
@Api(value = "捐赠api", tags = {"捐赠API"})
@Slf4j
@Controller
@RequestMapping(value = "/api/contribute")
public class ContributeProjectApiController {
    private final static Logger logger = LoggerFactory.getLogger(ContributeProjectApiController.class);
    @Autowired
    KjContributeProjectService kjContributeProjectService;
    @Autowired
    KjProjectTeamService kjProjectTeamService;

    @Autowired
    KjTeamMemberService kjTeamMemberService;
    @Autowired
    KjMemberIntegralHistoryService kjMemberIntegralHistoryService;

    @ApiOperation(value = "获取捐赠项目类型", notes = "获取捐赠项目类型")
    @GetMapping(value = "projectTypeList")
    public ResponseBean<List<DictResponseVo>> projectTypeList() {
        List<DictData> dictList = DictUtils.getDictList("project_type");
        List<DictResponseVo> vos = ListUtils.newArrayList();
        for (DictData dict: dictList
        ) {
            vos.add(new DictResponseVo(dict));
        }
        return new ResponseBean<>(vos);
    }

    @ApiOperation(value = "获取捐赠项目列表", notes = "获取捐赠项目列表")
    @GetMapping(value = "list")
    public ResponseBean<List<ProjectResponseVo>> list(ProjectListRequestVo vo) {
        List<KjContributeProject> activityList = kjContributeProjectService.findList(vo.convertToEntity());
        List<ProjectResponseVo> vos = ListUtils.newArrayList();
        for (KjContributeProject cp: activityList
        ) {
            vos.add(new ProjectResponseVo(cp));
        }
        return new ResponseBean<>(vos);
    }


    @ApiOperation(value = "获取项目详情", notes = "获取项目详情")
    @GetMapping(value = "{id}")
    public ResponseBean<ProjectDetailResponseVo> detail(@PathVariable(name = "id") String id, HttpServletRequest httpServletRequest) {
        KjContributeProject cp = kjContributeProjectService.get(id);
        ProjectDetailResponseVo result = new ProjectDetailResponseVo(cp);
        String token = httpServletRequest.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)) {
            String memberId = TokenUtils.verify(token);
            result.setIsLike(LikesUtil.getIsLike(id, memberId));
        }else{
            result.setIsLike("0");
        }
        return new ResponseBean<>(result);
    }


    @ApiOperation(value = "获取用户在项目下是否有团队", notes = "获取用户在项目下是否有团队")
    @GetMapping(value = "{id}/team")
    @UserLoginToken
    public ResponseBean<TeamResponseVo> team(@ApiIgnore @CurrentUser String memberId, @PathVariable(name = "id") String id) throws FreezMemberException {
        KjMember currentMember = KjMemberUtil.getCurrentMember(memberId);
        String teamId = TeamUtil.getMemberTeamId(currentMember, id);
        KjProjectTeam pt = kjProjectTeamService.get(teamId);
        if(pt != null) {
            return new ResponseBean<>(new TeamResponseVo(pt));
        }else{
            return new ResponseBean<>(new TeamResponseVo());
        }
    }



    @ApiOperation(value = "捐赠积分", notes = "捐赠积分")
    @UserLoginToken
    @PostMapping(value = "{id}/contribute")
    public ResponseBean<String> contribute(@ApiIgnore @CurrentUser String memberId, @PathVariable(name = "id") String id, BigDecimal integrals) throws FreezMemberException {
        KjMember currentMember = KjMemberUtil.getCurrentMember(memberId);
        KjContributeProject cp = kjContributeProjectService.get(id);
        if(kjContributeProjectService.getLastContributeIntegrals(cp).compareTo(integrals) < 0){
            return new ResponseBean(Global.FALSE, "-10", "捐赠积分大于项目所需积分");
        }
        try {
            String teamId = TeamUtil.getMemberTeamId(currentMember, id);
            if(StringUtils.isNotBlank(teamId)) {
                IntegralUtil.subtractIntegrals(currentMember, cp.getId() + "-" + teamId, IntegralEnum.TEAMCONTRIBUTE, integrals, cp.getName());
                kjProjectTeamService.updateContribute(teamId);
            }else{
                IntegralUtil.subtractIntegrals(currentMember, cp.getId(), IntegralEnum.CONTRIBUTE, integrals, cp.getName());
            }
            //更新项目的积分
            kjContributeProjectService.updateContributeMember(id);
            return new ResponseBean<>(Global.TRUE, "捐赠成功");
        } catch (LowIntegralException e) {
            return new ResponseBean(Global.FALSE, "", e.getMessage());
        }
    }


    @ApiOperation(value = "项目个人排行", notes = "项目个人排行")
    @GetMapping(value = "{id}/rank")
    public ResponseBean<RankListResponseVo> rank(@PathVariable(name = "id") String id, int pageNo, int pageSize, HttpServletRequest httpServletRequest) throws FreezMemberException {
        String token = httpServletRequest.getHeader("Authorization");
        KjMemberIntegralHistory h = new KjMemberIntegralHistory();
        h.setRelationId(id);
        RankListResponseVo result = new RankListResponseVo();
        // 执行认证
        if (StringUtils.isNotBlank(token)) {
            String memberId = TokenUtils.verify(token);
            KjMember currentMember = KjMemberUtil.getCurrentMember(memberId);
            if(currentMember != null) {
                h.setKjMember(currentMember);
                MemberIntegralRank myRank = kjMemberIntegralHistoryService.memberContributeRankNum(h);
                result.setMyRank(myRank);
            }
        }

        Page<KjMemberIntegralHistory> page = new Page(pageNo, pageSize);
        h.setPage(page);
        List<MemberIntegralRank> rankList = kjMemberIntegralHistoryService.getMemberContributeRank(h);
        result.setRankList(rankList);
        return new ResponseBean<>(result);
    }

    @ApiOperation(value = "项目团队捐赠排行", notes = "项目团队捐赠排行")
    @GetMapping(value = "{id}/teamRank")
    public ResponseBean<TeamRankListResponseVo> teamRank(@PathVariable(name = "id") String id, int pageNo, int pageSize,  HttpServletRequest httpServletRequest) throws FreezMemberException {
        String token = httpServletRequest.getHeader("Authorization");
        KjMemberIntegralHistory h = new KjMemberIntegralHistory();
        TeamRankListResponseVo result = new TeamRankListResponseVo();
        // 执行认证
        if (StringUtils.isNotBlank(token)) {
            String memberId = TokenUtils.verify(token);
            KjMember currentMember = KjMemberUtil.getCurrentMember(memberId);
            String teamId = TeamUtil.getMemberTeamId(currentMember, id);
            if(StringUtils.isNotBlank(teamId)) {
                h.setCreateBy(teamId);
                TeamContributeRank myRank = kjMemberIntegralHistoryService.getMemberTeamContributeRank(h);
                result.setMyRank(myRank);
            }else{
                result.setMyRank(new TeamContributeRank(currentMember));
            }
        }
        h.setRelationId(id);

        Page<KjMemberIntegralHistory> page = new Page(pageNo, pageSize);
        h.setPage(page);
        List<TeamContributeRank> rankList = kjMemberIntegralHistoryService.getTeamContributeRank(h);
        result.setRankList(rankList);
        return new ResponseBean<>(result);
    }

    @ApiOperation(value = "我捐赠的项目", notes = "我捐赠的项目")
    @PostMapping(value = "my")
    @UserLoginToken
    public ResponseBean<DataListPageVo> my(@ApiIgnore @CurrentUser String memberId, int year, int month, int pageNo, int pageSize) {
        Page<MemberProjectResponseVo> page = new Page<>(pageNo, pageSize);
        page.setList(kjContributeProjectService.memberContributeProjects(memberId, year, month));
        DataListPageVo vos = new DataListPageVo<>();
        vos.setCount(page.getCount());
        vos.setList(page.getList());
        vos.setPageNo(page.getPageNo());
        vos.setPageSize(page.getPageSize());
        return new ResponseBean<>(vos);
    }





}
